﻿using Newtonsoft.Json;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Qiniu2
{
    public class QiniuUploadHelper
    {
        public static string acc_key = "";
        public static string sec_key = "";

        /// <summary>
        /// 上传文件到七牛云
        /// </summary>
        /// <param name="image_data">图片数据</param>
        /// <param name="extend_name">扩展名eg: .jpg</param>
        /// <param name="bucketName"></param>
        /// <param name="type">子文件夹名称</param>
        /// <returns></returns>
        public static string UploadFile(byte[] image_data, string extend_name, string bucketName = "test", string type = "xxx")
        {
            PutPolicy policy = new PutPolicy() { Scope = bucketName };
            policy.SetExpires(100);

            Mac mac = new Mac(acc_key, sec_key);
            string token = Auth.CreateUploadToken(mac, JsonConvert.SerializeObject(policy));

            // 方式1：使用UploadManager
            //默认设置 Qiniu.Common.Config.PUT_THRESHOLD = 512*1024;
            //可以适当修改,UploadManager会根据这个阈值自动选择是否使用分片(Resumable)上传    
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_South;
            UploadManager um = new UploadManager(config);

            // 文件名
            string key = type + "/" + DateTime.Now.ToString("yyyyMMdd") + "_" + Guid.NewGuid().ToString("N") + extend_name;
            var result = um.UploadData(image_data, key, token, new PutExtra());
            if (result.Code == 200)
            {
                // 图片地址
                string pic_url = "/" + key;

                return pic_url;
            }
            else
            {
                return string.Empty;
            }
        }
    }
}

